%%%-------------------------------------------------------------------
%%% @author wukai
%%% @copyright (C) 2017, <COMPANY>
%%% @doc
%%%
%%% @end
%%% Created : 30. 十一月 2017 16:58
%%%-------------------------------------------------------------------
-module(mqtt_websocket).
-author("wukai").
-include("../include/mqtt_protocol.hrl").
-export([init/2]).
-export([websocket_init/1]).
-export([websocket_handle/2]).
-export([websocket_info/2]).

init(Req, Opts) ->
  log:log("sec-websocket-protocol ~p",[cowboy_req:parse_header(<<"sec-websocket-protocol">>, Req)]),
  State =#state{link_type = websocket,packetids = []},
  case cowboy_req:parse_header(<<"sec-websocket-protocol">>, Req) of
    undefined -> {cowboy_websocket, Req, State};
    Subprotocols ->
      case lists:member(<<"mqtt">>, Subprotocols) of
        true ->
          Req2 = cowboy_req:set_resp_header(<<"sec-websocket-protocol">>,
            <<"mqtt">>, Req),
          {cowboy_websocket, Req2, State};
        false ->
          {stop, Req, State}
      end
  end.

websocket_init(State) ->
  log:log("websocket state ~p",[State]),
  {ok, State}.

websocket_handle({text, Msg}, State) ->
  {reply, {text, << "That's what she said! ", Msg/binary >>}, State};

websocket_handle({binary,Bin}, State) ->
  NewState =mqtt_protocol:rec_bin(websocket,State,Bin),
  {ok, NewState}.

websocket_info({timeout, _Ref, Msg}, State) ->
  {reply, {text, Msg}, State};
websocket_info({publish, _Ref, Msg}, State) ->
  NState = mqtt_protocol:publish_msg(websocket,State,Msg),
  {ok, NState};
websocket_info({send_bin, Msg}, State) ->
  {reply, {binary, Msg}, State};
websocket_info(_Info, State) ->
  {ok, State}.
